#include <iostream>

using std::cout;
using std::endl;

//单例模式的自动释放第二种形式：内部类 + 静态数据成员
class Singleton
{
public:
    static Singleton *getInstance()
    {
        if(nullptr == _pInstance)
        {
            _pInstance = new Singleton();
        }
        return _pInstance;
    }
private:
    class AutoRelease
    {
    public:
        AutoRelease()
        {
            cout << "AutoRelease()" << endl;
        }
    
        ~AutoRelease()
        {
            cout << "~AutoRelease()" << endl;
            if(_pInstance)
            {
                delete _pInstance;
                _pInstance = nullptr;
            }
        }
    };
private:
    Singleton()
    {
        cout <<"Singleton()" << endl;
        /* AutoRelease ar; */
    }

    ~Singleton()
    {
        cout <<"~Singleton()" << endl;
    }

private:
    static Singleton *_pInstance;
    static AutoRelease _ar;
};

/* Singleton *Singleton::_pInstance = nullptr; */
Singleton *Singleton::_pInstance = getInstance();
Singleton::AutoRelease Singleton::_ar;

void test()
{
    Singleton::getInstance();
    /* Singleton::AutoRelease ar;//创建栈对象error */
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

